﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Web.UI.WebControls;
using Hematology.Data;
using Hematology.Tools;
using Hematology.Tools.Text;
using Hematology.UserSite.Controls;
using NgoResource = Hematology.UserSite.App_GlobalResources.UserSite;

namespace Hematology.UserSite.admin
{
	public partial class EditEvent : NgoPage
	{
		#region Properties

		protected EnumHelper.EventType CurrentEventType
		{
			get
			{
				return ViewState["CurrentEventType"] != null
						   ? (EnumHelper.EventType)Enum.Parse(typeof(EnumHelper.EventType), ViewState["CurrentEventType"].ToString())
						   : EnumHelper.EventType.Congress;
			}
			set { ViewState["CurrentEventType"] = value; }
		}

		private EnumHelper.PageSection CurrentPageSection
		{
			get
			{
				return ViewState["CurrentPageSection"] != null
						   ? (EnumHelper.PageSection)Enum.Parse(typeof(EnumHelper.PageSection), ViewState["CurrentPageSection"].ToString())
						   : EnumHelper.PageSection.List;
			}
			set { ViewState["CurrentPageSection"] = value; }
		}

		private SiteEvent CurrentEvent
		{
			get { return (SiteEvent)ViewState["CurrentEvent"]; }
			set { ViewState["CurrentEvent"] = value; }
		}

		private string ListUrl
		{
			get { return String.Format("/admin/EditEvent.aspx?et={0}&view=List", CurrentEventType); }
		}

		#endregion

		#region Fill methods

		private void FillEditForm()
		{
			string sEventId = Request.QueryString["id"];
			int iEventId;
			if (!String.IsNullOrEmpty(sEventId) && Int32.TryParse(sEventId, out iEventId))
			{
				SiteEvent oSiteEvent = SiteEvent.Get(iEventId);
				if (oSiteEvent != null)
				{
					CurrentEvent = oSiteEvent;
					FillFileAttachList(iEventId);

					txtSiteEventTitle.Text = oSiteEvent.Title;
					txtSiteEventPlace.Text = oSiteEvent.EventPlace;
					ckedSiteEvent.Text = oSiteEvent.EventContent;

					if (oSiteEvent.StartDate.HasValue)
						cpStartDate.SelectedValue = oSiteEvent.StartDate;

					if (oSiteEvent.FinishDate.HasValue)
						cpFinishDate.SelectedValue = oSiteEvent.FinishDate;

					if (oSiteEvent.IsVisible != null)
						checkIsVisible.Checked = oSiteEvent.IsVisible.Value;
				}
			}
		}

		private void FillEventList()
		{
			List<SiteEvent> lstSiteEvent = SiteEvent.ListAllEvents((int)CurrentEventType, false);
			rptSiteEvent.DataSource = lstSiteEvent;
			rptSiteEvent.DataBind();
		}

		private void FillPage()
		{
			switch (CurrentPageSection)
			{
				case EnumHelper.PageSection.Edit:
				case EnumHelper.PageSection.Add:
					ToolbarSetup();
					FillEditForm();

					mvEvents.ActiveViewIndex = 1;

					break;
				default:
					FillEventList();

					mvEvents.ActiveViewIndex = 0;

					break;
			}
		}

		private void FillViewStateVariables()
		{
			string pageSection = Request.QueryString["view"];
			if (Array.IndexOf(Enum.GetNames(typeof(EnumHelper.PageSection)), pageSection) > -1)
			{
				CurrentPageSection =
					(EnumHelper.PageSection)Enum.Parse(typeof(EnumHelper.PageSection), pageSection);
			}

			string EventType = Request.QueryString["et"];
			if (Array.IndexOf(Enum.GetNames(typeof(EnumHelper.EventType)), EventType) > -1)
			{
				CurrentEventType =
					(EnumHelper.EventType)Enum.Parse(typeof(EnumHelper.EventType), EventType);
				ptTitle.DataBind();
			}
		}

		private void FillFileAttachList(int siteContentId)
		{
			btnSaveAttach.Visible = true;

			List<FileAttach> listFileAttach = FileAttach.ListByEventId(siteContentId);
			if (listFileAttach != null)
			{
				rptContentAttach.DataSource = listFileAttach;
				rptContentAttach.DataBind();
			}
		}

		#endregion

		#region Other methods

		private void ToolbarSetup()
		{
			ckedSiteEvent.config.skin = "office2003";
			ckedSiteEvent.config.toolbar = PageHelper.EditorButtonSet;

			ckedSiteEvent.DisableObjectResizing = true;
			ckedSiteEvent.ResizeEnabled = false;
			ckedSiteEvent.Width = 904;
			ckedSiteEvent.Height = 600;
		}

		private void SaveAttach(int iEventId)
		{
			if (String.IsNullOrEmpty(fuAttachFile.FileName))
				return;

			if (!fuAttachFile.HasFile || !FileValidate(fuAttachFile.PostedFile.ContentType))
				return;

			string sFullPath = Path.Combine(Server.MapPath(ConfigReader.EventAttachmentPath), fuAttachFile.FileName);

			FileStream fsWriteAttachmentStream = new FileStream(sFullPath, FileMode.Create, FileAccess.ReadWrite);
			using (BinaryWriter binWriter = new BinaryWriter(fsWriteAttachmentStream))
			{
				binWriter.Write(FileHelper.ReadFileContent(fuAttachFile.PostedFile.InputStream));
				binWriter.Close();
			}

			if (!File.Exists(sFullPath))
				return;

			FileAttach emailTemplateAttach = new FileAttach
			{
				EventId = iEventId,
				DocumentName = fuAttachFile.FileName,
				DocumentType = fuAttachFile.PostedFile.ContentType,
				DocumentSize = fuAttachFile.PostedFile.ContentLength
			};

			emailTemplateAttach.Save();
			if (!emailTemplateAttach.AttachId.HasValue)
				return;

			FillFileAttachList(iEventId);
		}

		protected bool FileValidate(string sContentType)
		{
			string[] sGrantedTypes = TextHelper.AllowedFileTypes;
			return Array.IndexOf(sGrantedTypes, sContentType) != -1;
		}

		private void SetTitle()
		{
			string sBaseTitleString = string.Format("{0} \"{1}\"", NgoResource.resPartManager,
													NgoResource.ResourceManager.GetString(
														string.Format("resTopic{0}", CurrentEventType.ToString())));

			switch (CurrentPageSection)
			{
				case EnumHelper.PageSection.Edit:
					ptTitle.Text = string.Format("{0} - {1}", sBaseTitleString, NgoResource.resEdit);
					break;
				case EnumHelper.PageSection.Add:
					ptTitle.Text = string.Format("{0} - {1}", sBaseTitleString, NgoResource.resNew);
					break;
				default:
					ptTitle.Text = string.Format("{0} - {1}", sBaseTitleString, NgoResource.resList);
					break;
			}
		}

		#endregion

		#region Event handlers

		protected void Page_Load(object sender, EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				FillViewStateVariables();
				FillPage();
			}

			SetTitle();
		}

		protected void btnSave_Click(object sender, EventArgs e)
		{
			if (!Page.IsValid)
				return;

			if (CurrentPageSection == EnumHelper.PageSection.Add)
			{
				SiteEvent siteEvent = new SiteEvent
										{
											EventContent = ckedSiteEvent.Text,
											EventPlace = txtSiteEventPlace.Text,
											Title = txtSiteEventTitle.Text.Trim(),
											StartDate = cpStartDate.SelectedValue,
											FinishDate = cpFinishDate.SelectedValue,
											EventTypeCode = (int)CurrentEventType,
											IsVisible = checkIsVisible.Checked
										};

				siteEvent.Save();

				if (siteEvent.EventId != null)
				{
					SaveAttach(siteEvent.EventId.Value);

					if (cbCloseAfterSave.Checked)
						Response.Redirect(ListUrl);
				}
			}
			else
			{
				CurrentEvent.EventContent = ckedSiteEvent.Text;
				CurrentEvent.EventPlace = txtSiteEventPlace.Text;
				CurrentEvent.Title = txtSiteEventTitle.Text.Trim();
				CurrentEvent.StartDate = cpStartDate.SelectedValue;
				CurrentEvent.FinishDate = cpFinishDate.SelectedValue;
				CurrentEvent.EventTypeCode = (int)CurrentEventType;
				CurrentEvent.CreateDate = CurrentEvent.CreateDate;
				CurrentEvent.IsVisible = checkIsVisible.Checked;

				CurrentEvent.UpdateInstance();

				if (cbCloseAfterSave.Checked)
					Response.Redirect(ListUrl);
			}
		}

		protected void btnList_Click(object sender, EventArgs e)
		{
			Response.Redirect(ListUrl);
		}

		protected void rptSiteEvent_ItemCommand(object source, RepeaterCommandEventArgs e)
		{
			if (e.CommandName == "DeleteEvent")
			{
				int iEventId = Convert.ToInt32(e.CommandArgument);
				SiteEvent siteEvent = SiteEvent.Get(iEventId);
				siteEvent.IsDeleted = true;

				siteEvent.UpdateInstance();

				FillEventList();
			}
		}

		protected void rptContentAttach_ItemCommand(object source, RepeaterCommandEventArgs e)
		{
			if (e.CommandName == "DeleteAttach")
			{
				int iAttachId = Convert.ToInt32(e.CommandArgument);
				FileAttach fileAttach = FileAttach.Get(iAttachId);
				fileAttach.IsDeleted = true;

				fileAttach.UpdateInstance();

				if (CurrentEvent.EventId != null)
				{
					FillFileAttachList(CurrentEvent.EventId.Value);
				}
			}
			else if (e.CommandName == "OpenAttach")
			{
				int iAttachId = Convert.ToInt32(e.CommandArgument);
				FileAttach fileAttach = FileAttach.Get(iAttachId);
				if (fileAttach != null)
				{
					Response.Redirect(Path.Combine(ConfigReader.EventAttachmentPath, fileAttach.DocumentName));
				}
			}
		}

		protected void btnSaveAttach_Click(object sender, EventArgs e)
		{
			if (CurrentEvent != null && CurrentEvent.EventId.HasValue)
			{
				SaveAttach(CurrentEvent.EventId.Value);
			}
		}

		#endregion
	}
}